package top.huntwolf.admin.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import top.huntwolf.admin.pojo.cmsUser.CMSUser;
import top.huntwolf.admin.service.CMSUserService;


//只会在登录时进入该realm进行授权验证
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private CMSUserService cmsUserService;

    /**
     * 限定只能处理自定义JWTtoken
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param auth 此处为shiro提供的UsernamePasswordToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {

        String principal = (String) auth.getPrincipal();
        CMSUser user = cmsUserService.findUserByName(principal);

        //用户不存在
        if (user == null) {
            throw new UnknownAccountException();
        }

        return new SimpleAuthenticationInfo(user,user.getUserPwd(),ByteSource.Util.bytes(user.getSalt()),getName());

    }
}
